/**
 * VUEshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.vueshop.com.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: soubao-java 2020-07-22 $
 */<template>
  <div>
    <div>
      <div class="fixed-bar">
        <div class="item-title">
          <router-link class="back" :to="{name:'newbie_coupons'}" title="返回列表">
            <i class="fa fa-arrow-circle-o-left"></i>
          </router-link>
          <div class="subject">
            <h3>优惠券管理 - 编辑新人优惠券</h3>
            <h5>网站系统新人优惠券管理</h5>
          </div>
        </div>
      </div>
      <form :model="form">
        <div class="ncap-form-default">
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>优惠券名称
              </label>
            </dt>
            <dd class="opt">
              <input v-model="form.name" type="text" class="input-txt" />
              <p class="err-msg" v-if="errResult.name && !form.name">{{errResult.name}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>优惠券面额
              </label>
            </dt>
            <dd class="opt">
              <input v-model="form.money" type="text" class="input-txt" />
              <p class="err-msg" v-if="errResult.money">{{errResult.money}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>消费金额
              </label>
            </dt>
            <dd class="opt">
              <input v-model="form.condition" type="text" class="input-txt" />
              <p class="err-msg" v-if="errResult.condition">{{errResult.condition}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>发放起始日期
              </label>
            </dt>
            <dd class="opt">
              <div class="block">
                <el-date-picker
                  size="mini"
                  v-model="beginTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="timestamp"
                ></el-date-picker>
              </div>
              <p
                class="err-msg"
                v-if="errResult.send_start_time && !form.send_start_time"
              >{{errResult.send_start_time}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>发放结束日期
              </label>
            </dt>
            <dd class="opt">
              <div class="block">
                <el-date-picker
                  size="mini"
                  v-model="endTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  value-format="timestamp"
                ></el-date-picker>
              </div>
              <p
                class="err-msg"
                v-if="errResult.send_end_time && !form.send_end_time"
              >{{errResult.send_end_time}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>使用有效期
              </label>
            </dt>
            <dd class="opt">
              <input
                v-model="form.validity_day"
                type="text"
                onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"
              />天
              <p
                class="err-msg"
                v-if="errResult.validity_day && !form.validity_day"
              >{{errResult.validity_day}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>
                <em>*</em>可使用商品：
              </label>
            </dt>
            <dd class="opt">
              <el-radio-group v-model="form.use_type">
                <el-radio :label="0">全店通用</el-radio>
                <label class="el-radio" @click="drawer = true">
                  <el-radio :label="1">指定商品</el-radio>
                </label>
                <el-radio :label="2">指定分类</el-radio>
              </el-radio-group>
              <p class="err-msg" v-if="errResult.use_type && !form.use_type">{{errResult.use_type}}</p>
            </dd>
          </dl>
          <dl class="row" v-if="form.use_type == 1">
            <dt class="tit">
              <label>指定商品列表</label>
            </dt>
            <dd class="opt">
              <el-table :data="form.goods_list" style="width: 100%;">
                <el-table-column label="商品ID" prop="goods_id" width="130"></el-table-column>
                <el-table-column label="商品名称" prop="goods_name" width="130" show-overflow-tooltip></el-table-column>
                <el-table-column
                  label="价格"
                  prop="shop_price"
                  width="100"
                  :formatter="toFixedShopPrice"
                ></el-table-column>
                <el-table-column label="库存" prop="store_count" width="100"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" @click="deleteConfig(scope.$index, scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <p
                class="err-msg"
                v-if="errResult.goods_list && form.goods_list == 0"
              >{{errResult.goods_list}}</p>
            </dd>
          </dl>
          <dl class="row" v-if="form.use_type == 2">
            <dt class="tit">
              <label>
                <em>*</em>限制商品分类使用：
              </label>
            </dt>
            <dd class="opt">
              <el-cascader
                size="small"
                v-model="form.goods_category_id"
                :options="goodsCategoryTree"
                :props="{ emitPath: false, label: 'name', value: 'id' }"
              ></el-cascader>
              <p
                class="err-msg"
                v-if="errResult.goods_category_id && !form.goods_category_id"
              >{{errResult.goods_category_id}}</p>
            </dd>
          </dl>
          <dl class="row">
            <dt class="tit">
              <label>状态</label>
            </dt>
            <dd class="opt">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">有效</el-radio>
                <el-radio :label="2">无效</el-radio>
              </el-radio-group>
            </dd>
          </dl>
          <div class="bot">
            <el-button type="primary" @click="onSubmit()" :loading="isLoading">确认提交</el-button>
          </div>
        </div>
      </form>
	  <el-drawer
	    title="选择商品"
	    direction="ltr"
	    :visible.sync="drawer"
	    size="1000"
		:modal-append-to-body="false"
	    @open="currentPage = 1;getGoodsPage()"
	  >
	  	<div class="searchbox">
	  	  <el-cascader
	  	    size="small"
	  	    clearable
	  	    filterable
	  	    placeholder="商品分类"
	  	    v-model="categoryId"
	  	    :options="goodsCategoryTree"
	  	    :props="{label: 'name', value: 'id', checkStrictly: true}"
	  	  ></el-cascader>
	  	  <el-select v-model="brandId" size="small" filterable clearable placeholder="品牌">
	  	    <el-option
	  	      v-for="item in brandList"
	  	      :key="item.id"
	  	      :label="item.name"
	  	      :value="item.id"
	  	    ></el-option>
	  	  </el-select>
	  	  <el-input
	  	    class="searchinput"
	  	    v-model="goodsName"
	  	    width="10"
	  	    size="small"
	  	    placeholder="商品名称"
	  	    clearable
	  	  />
	  	  <el-button
	  	    class="searchbtn"
	  	    size="small"
	  	    icon="el-icon-search"
	  	    @click="currentPage = 1;getGoodsPage()"
	  	  >搜索</el-button>
	  	</div>
	  	<div class="tablebox">
	  	  <el-table :data="page.records" ref="multipleTable" row-key="goods_id" @selection-change="selectionGoodsListChange">
	  	    <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
	  	    <el-table-column property="goods_id" label="商品ID" width="140"></el-table-column>
	  	    <el-table-column property="goods_name" label="商品名称" width="260" show-overflow-tooltip></el-table-column>
	  	    <el-table-column property="shop_price" label="价格" width="120"></el-table-column>
	  	    <el-table-column property="store_count" label="库存"></el-table-column>
	  	  </el-table>
	  	  <el-pagination
	  	    background
	  	    class="paginationbox"
	  	    @size-change="handleSizeChange"
	  	    @current-change="handleCurrentChange"
	  	    :current-page="currentPage"
	  	    :page-sizes="[10, 15, 20]"
	  	    :page-size="pageSize"
	  	    layout="total, sizes, prev, pager, next, jumper"
	  	    :total="page.total"
	  	  ></el-pagination>
	  	</div>
	  </el-drawer>
    </div>
  </div>
</template>

<script>
import {
  getStoreCoupon,
  getGoodsIPage,
  getGoodsCategoryTree,
  updateStoreCoupon,
  getBrandList,
  addCoupon
} from "@/utils/api";
export default {
  data() {
    return {
      page: {
        total: 0
      },
	  drawer: false,
      currentPage: this.$route.params.currentPage || 1,
      pageSize: 10,
      id: null,
      form: {
        goods_category: {
          id: null,
          parent_ids: []
        },
        goods_list: []
      },
      dialogTableVisible: false,
      beginTime: null,
      endTime: null,
      isLoading: false,
      errResult: { goods_list: null, goods_category_id: null },
      categoryId: null,
      goodsCategoryTree: [], //商品分类
      brandId: null,
      brandList: null,
      goodsName: "",
	  isAddToTableSelection: false,
    };
  },
  created() {
    if (this.$route.params.id) {
      //编辑
      this.id = this.$route.params.id;
      this.getCoupon();
    }
	this.getGoodsCategoryTree();
	this.getBrandList();
  },
  methods: {
    handleSizeChange(e) {
      this.pageSize = e;
      this.getGoodsPage();
    },
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getGoodsPage();
    },
    getCoupon() {
      var that = this;
      getStoreCoupon({ id: this.id }).then(function(res) {
        that.form = res;
        that.beginTime = res.send_start_time * 1000;
        that.endTime = res.send_end_time * 1000;
        //回显分类
        if (res.goods_category) {
          that.form.goods_category_id =
            res.goods_category.parent_ids[
              res.goods_category.parent_ids.length - 1
            ];
        }
      });
    },
    getGoodsPage() {
      var that = this;
      getGoodsIPage({
        cat_id:
          this.categoryId == null
            ? null
            : this.categoryId[this.categoryId.length - 1],
        brand_id: this.brandId,
        goods_name: this.goodsName,
        p: that.currentPage,
        size: that.pageSize
      }).then(function(res) {
        that.page = res;
		if (!that.isAddToTableSelection) {
		  that.isAddToTableSelection = true;
		  //活动未结束，商品还存在于活动中，在选择商品table中加入该商品数据并勾选该活动的商品
		  if (that.form.goods_list.length > 0) {
		    that.form.goods_list.forEach(e => {
		      that.$refs.multipleTable.selection.push(e);
		    });
		  }
		}
      });
    },
	//选择商品
	selectionGoodsListChange(selectionRows) {
	  //已勾选的商品，如果未添加到活动商品集合中，则进行添加操作；未勾选的商品，如果之前已加入，则移除；
	  this.page.records.forEach(goods => {
	    //判断商品是否勾选
	    let checked = false;
	    selectionRows.forEach(selectGoods => {
	      if (selectGoods.goods_id == goods.goods_id) {
	        checked = true;
	        return false;
	      }
	    });
	    //判断该商品是否已加入活动商品集合
	    let isAdd = false;
		this.form.goods_list.forEach((e, i) => {
		  if (e.goods_id == goods.goods_id) {
		    isAdd = true;
		    //已加入
		    //未勾选，移除之
		    if (!checked) {
		      this.form.goods_list.splice(i, 1);
		    }
		    return false;
		  }
		});
	    //未加入，已勾选，将商品添加到活动商品中
	    if (!isAdd && checked) {
	      this.form.goods_list.push({
			goods_id: goods.goods_id,
	        goods_name: goods.goods_name,
	        store_count: goods.store_count,
	        shop_price: goods.shop_price
	      });
	    }
	  });
	},
	deleteConfig(index, row) {
	  this.form.goods_list.splice(index, 1);
	  //从活动商品中删除，并在table中把选中状态一并移除
	    if (!this.$refs.multipleTable) {
	      return;
	    }
	    let goodsSelection = this.$refs.multipleTable.selection;
	    goodsSelection.forEach((e, i) => {
	      if (e.goods_id == row.goods_id) {
	        goodsSelection.splice(i, 1);
	        return false;
	      }
	    });
	},
    getGoodsCategoryTree() {
      var that = this;
      getGoodsCategoryTree({
        levels: "1,2,3"
      }).then(function(res) {
        that.goodsCategoryTree = res;
      });
    },
    getBrandList() {
      var that = this;
      getBrandList().then(function(res) {
        that.brandList = res;
      });
    },
    onSubmit() {
      if (this.form.use_type == 1) {
        if (this.form.goods_list == null || this.form.goods_list.length == 0) {
          this.$message.error("参数错误");
          this.errResult.goods_list = "指定商品不能为空";
          return;
        }
      } else if (this.form.use_type == 2) {
        if (this.form.goods_category_id == null) {
          this.$message.error("参数错误");
          this.errResult.goods_category_id = "指定分类不能为空";
          return;
        }
      }
      var that = this;
      this.form.send_start_time =
        this.beginTime == null ? null : this.beginTime / 1000;
      this.form.send_end_time =
        this.endTime == null ? null : this.endTime / 1000;
      this.isLoading = true;
	  if (typeof this.$route.params.id != "undefined") {
		  updateStoreCoupon(that.form).then(function(res) {
		    if (res.status == 1) {
		      that.$message.success({
		        message: "保存成功",
		        duration: 1000,
		        onClose: function() {
		          that.$router.push({ name: "newbie_coupons" });
		        }
		      });
		    } else if (res.status == -1) {
		      that.$message.error("参数错误");
		      that.errResult = res.result;
		    } else {
		      that.$message.error(res.msg);
		    }
		    that.isLoading = false;
		  });
	  } else {
		  that.form.type = 4;
		  addCoupon(that.form).then(function(res) {
			if (res.status == 1) {
			    that.$message.success({
			      message: "保存成功",
			      duration: 1000,
			      onClose: function() {
			        that.$router.push({ name: "newbie_coupons" });
			      }
			    });
			  } else if (res.status == -1) {
			    that.$message.error("参数错误");
			    that.errResult = res.result;
			  } else {
			    that.$message.error(res.msg);
			  }
			  that.isLoading = false;
			});
	  }
    },
    toFixedShopPrice(row) {
      return row.shop_price.toFixed(2);
    }
  }
};
</script>

<style scoped>
.searchinput {
  width: auto;
}
>>>.el-pagination__sizes .el-input .el-input__inner {
    font-size: 13px;
    padding-left: 8px;
    width: 150px;
}
>>>.el-input--mini .el-input__inner {
    height: 28px;
    line-height: 28px;
    width: 220px;
}
</style>
